//
//  DeviceSettingVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/5/26.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "DeviceSettingVC.h"
#import "DeviceSetPwdVC.h"
#import "DeviceRenameVC.h"

@interface DeviceSettingVC () {
    DeviceItem *mDeviceItem;
    BOOL mblMining;
}

@property(weak, nonatomic) IBOutlet UIButton *backBt;
@property(weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property(strong, nonatomic) UILabel  *nameLb;
@property(strong, nonatomic) UILabel  *statusLb;
@property(strong, nonatomic) UIButton *switchBt;
@property(strong, nonatomic) UILabel  *versionLb;

@end

@implementation DeviceSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
    [self updateView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setData:(DeviceItem *) deviceItem {
    mDeviceItem = deviceItem;
}

- (void)initView {
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    float width = [UIScreen mainScreen].bounds.size.width-72;
    float height = 0;
    float originY = 0;
    
    originY +=height;
    float margin1 = 9;
    float margin2 = 4;
    float h = 45;
    float topMargin[] = {margin1, margin2, margin1, margin1, margin2, margin2};
    NSString *titles[] = {@"设备名称",@"设备状态",@"开启挖矿",@"修改设备管理密码",@"重启设备",@"加速器固件版本"};
    for (int i=0; i<6; i++) {
        originY += topMargin[i];
        UIButton *bt = [[UIButton alloc] initWithFrame:CGRectMake(0, originY, width, h)];
        [bt setBackgroundColor:[UIColor whiteColor]];
        bt.layer.cornerRadius = globalRadius;
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 200, h)];
        lb.text = titles[i];
        [lb setFont:[UIFont systemFontOfSize:14]];
        lb.textColor = colorWithString(@"#4f525b");
        [bt addSubview:lb];
        float imgH = 12;
        float imgW = imgH*20/42;
        if (i == 3 || i == 4) {
            UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(width-imgW-10, h/2-imgH/2, imgW, imgH)];
            [iv setImage:[UIImage imageNamed:@"img_jt_1"]];
            [bt addSubview:iv];
        }
        if (i==0) {
            self.nameLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width-10, h)];
            self.nameLb.textAlignment = NSTextAlignmentRight;
            self.nameLb.font = [UIFont systemFontOfSize:14];
            self.nameLb.textColor = colorWithString(@"#a2b4cd");
            [bt addSubview:self.nameLb];
        }
        if (i==1) {
            self.statusLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width-10, h)];
            self.statusLb.textAlignment = NSTextAlignmentRight;
            self.statusLb.font = [UIFont systemFontOfSize:14];
            self.statusLb.textColor = colorWithString(@"#559fff");
            [bt addSubview:self.statusLb];
        }
        if (i==2) {
            float btH = 20;
            float btW = btH*69/28;
            self.switchBt = [[UIButton alloc] initWithFrame:CGRectMake(width-10-btW, h/2-btH/2, btW, btH)];
            [self.switchBt setImage:[UIImage imageNamed:@"img_cb_ming_c"] forState:UIControlStateNormal];
            [bt addSubview:self.switchBt];
            [[self.switchBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
                if (self->mblMining) {
                    NSString *title = @"确认关闭挖矿吗？";
                    NSString *msg = @"关闭挖矿后，设备将不再产生收益";
                    UIAlertController *vc = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [vc addAction:cancel];
                    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                        [self requestForSwitch];
                    }];
                    [vc addAction:confirm];
//                    [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
                    [self presentViewController:vc animated:YES completion:nil];
                } else {
                    [self requestForSwitch];
                }
            }];
        }
        if (i==5) {
            self.versionLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width-10, h)];
            self.versionLb.textAlignment = NSTextAlignmentRight;
            self.versionLb.font = [UIFont systemFontOfSize:14];
            self.versionLb.textColor = colorWithString(@"#8d8d8d");
            self.versionLb.text = [NSString stringWithFormat:@"V%@", appVersion()];
            [bt addSubview:self.versionLb];
        }
        [[bt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            switch (i) {
                case 0: {
                    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    DeviceRenameVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceRenameVCID"];
                    [vc setData:self->mDeviceItem];
                    [self.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 1: {
                    
                    break;
                }
                case 2: {
                    
                    break;
                }
                case 3: {
                    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                    DeviceSetPwdVC *vc = [storyboard instantiateViewControllerWithIdentifier:@"DeviceSetPwdVCID"];
                    [vc setData:self->mDeviceItem];
                    [self.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 4: {
                    NSString *msg = @"重启设备可能需要一些时间，确定立即重启吗？";
                    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                        [self requestForRestart];
                    }];
                    [vc addAction:cancel];
                    [vc addAction:confirm];
                    [self presentViewController:vc animated:YES completion:nil];
                    break;
                }
                case 5: {
                    DeviceItem *item = self->mDeviceItem;
                    if (item.deviceState && item.romUpgradePlan && item.romUpgradePlan.version && item.romUpgradePlan.version.length>0) {
                        NSString *msg = [NSString stringWithFormat:@"版本：%@\n升级内容：%@\n\n升级会需要数分钟，升级过程中，请勿断电，否则路由将无法正常使用，您确定要升级吗？", item.romUpgradePlan.version, item.romUpgradePlan.changeLog];
                        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            [self requestForUpdate];
                        }];
                        [vc addAction:cancel];
                        [vc addAction:confirm];
                        [self presentViewController:vc animated:YES completion:nil];
                    } else {
                        [JPToast showText:@"还没有更新版本"];
                    }
                    
                    break;
                }
                default:
                    break;
            }
        }];
        [self.scrollView addSubview:bt];
        originY += h;
    }
    [self.scrollView setContentSize:CGSizeMake(0, originY)];
}

- (void)updateView {
    if (!mDeviceItem) {
        return;
    }
    self.nameLb.text = mDeviceItem.label ? mDeviceItem.label : mDeviceItem.sn;
    DeviceState *state = mDeviceItem.deviceState;
    mblMining = (state && [state.miningSwitch intValue] == 1) ? YES : NO;
    if (mDeviceItem.deviceOnlineState && [mDeviceItem.deviceOnlineState intValue] == 0) {
        self.statusLb.text = @"设备离线";
        self.statusLb.textColor = colorWithString(@"#FF0000");
    } else if (state) {
        if (!state.disks || (state.disks && state.disks.count<=0)) {
            self.statusLb.text = @"磁盘未接入";
            self.statusLb.textColor = colorWithString(@"#FF0000");
        } else if ([state.miningState intValue]== 1) {
            self.statusLb.text = @"正在挖矿";
            self.statusLb.textColor = colorWithString(@"#15c1ff");
        } else if ([state.miningSwitch intValue] == 0) {
            self.statusLb.text = @"挖矿未开启";
            self.statusLb.textColor = colorWithString(@"#2dff9e");
        } else {
            self.statusLb.text = @"挖矿故障";
            self.statusLb.textColor = colorWithString(@"#FF0000");
        }
    } else {
        self.statusLb.text = @"未知错误";
        self.statusLb.textColor = colorWithString(@"#FF0000");
    }
    self.versionLb.text = mDeviceItem.romVersion ? mDeviceItem.romVersion : @"--";
    mblMining = (state && [state.miningSwitch intValue] == 1) ? YES : NO;
    [self.switchBt setImage:[UIImage imageNamed:mblMining ? @"img_cb_ming_o" : @"img_cb_ming_c"] forState:UIControlStateNormal];
}

- (void)requestData {
    NSString *url = [NSString stringWithFormat:@"%@%@/state", d_detail, mDeviceItem.sn];
    [[[HttpRequest shareInstance] signGet:url map:nil] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            @try {
                if (x[@"data"]) {
                    NSDictionary *temp = x[@"data"];
                    NSError *error;
                    DeviceItem *deviceItem = [MTLJSONAdapter modelOfClass:[DeviceItem class] fromJSONDictionary:temp error:&error];
                    NSError *error2;
                    NSDictionary *temp2 = [temp objectForKey:@"deviceState"];
                    DeviceState *deviceState = nil;
                    NSArray *clients = nil;
                    NSArray *disk = nil;
                    RomUpgradePlan *romUpgradePlan = nil;
                    @try {
                        deviceState = [MTLJSONAdapter modelOfClass:[DeviceState class] fromJSONDictionary:temp2 error:&error2];
                    } @catch (NSException *exception) {
                        
                    }
                    NSError *error3;
                    NSError *error4;
                    if (isNil(temp2)) {
                        @try {
                            NSArray *temp3 = [temp2 objectForKey:@"clients"];
                            clients = [MTLJSONAdapter modelsOfClass:[Clinets class] fromJSONArray:temp3 error:&error3];
                            NSArray *temp4 = [temp2 objectForKey:@"disks"];
                            disk = [MTLJSONAdapter modelsOfClass:[Disks class] fromJSONArray:temp4 error:&error4];
                        } @catch (NSException *exception) {
                            
                        }
                    }
                    NSError *error5;
                    @try {
                        NSDictionary *temp5 = [temp objectForKey:@"romUpgradePlan"];
                        romUpgradePlan = [MTLJSONAdapter modelOfClass:[RomUpgradePlan class] fromJSONDictionary:temp5 error:&error5];
                    } @catch (NSException *exception) {
                        
                    }
                    if (!error) {
                        if (!error2 && deviceState) {
                            if (!error3 && clients) {
                                deviceState.clients = clients;
                            }
                            if (!error4 && disk) {
                                deviceState.disks = disk;
                            }
                            deviceItem.deviceState = deviceState;
                        }
                        if (!error5) {
                            deviceItem.romUpgradePlan = romUpgradePlan;
                        }
                        self->mDeviceItem = deviceItem;
                    }
                    [self updateView];
                }
            } @catch (NSException *exception) {
                NSLog(@"error=%@",exception);
            }
        }
    }];
}

- (void)requestForSwitch {
    [self showLoading:@"提交中"];
    NSString *url = [NSString stringWithFormat:@"%@%@/cmd", d_cmd, mDeviceItem.sn];
    NSDictionary *dic = @{@"cmd": @"mining_switch", @"content": (!mblMining?@"1":@"0")};
    [[[HttpRequest shareInstance] signPost:url map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        if ([x[@"code"] intValue] == 200) {
            self->mblMining = !self->mblMining;
            if (self->mblMining) {
                [self.switchBt setImage:[UIImage imageNamed:@"img_cb_ming_o"] forState:UIControlStateNormal];
                NSString *title = @"开启挖矿成功！";
                NSString *msg = @"同步设备状态可能需要数分钟，请稍后查看";
                UIAlertController *vc = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [vc addAction:cancel];
                [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
                [self presentViewController:vc animated:YES completion:nil];
            } else {
                [JPToast showText:@"已关闭挖矿"];
                [self.switchBt setImage:[UIImage imageNamed:@"img_cb_ming_c"] forState:UIControlStateNormal];
            }
        } else {
            [JPToast showText:x[@"message"]];
        }
    } error:^(NSError *error) {
        [self hideLoading];
        [JPToast showText:@"网络错误"];
    }];
}

- (void)requestForRestart {
    [self showLoading:@"正在重启"];
    NSString *url = [NSString stringWithFormat:@"%@%@/cmd", d_cmd, mDeviceItem.sn];
    NSDictionary *dic = @{@"cmd": @"restart", @"content": @"1"};
    [[[HttpRequest shareInstance] signPost:url map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        if ([x[@"code"] intValue] == 200) {
//            [JPToast showText:@"发送重启成功，设备状态可能数分钟后恢复正常"];
//            发送重启成功，请稍后查看设备状态                   确定
//            NSString *title = @"开启挖矿成功！";
            NSString *msg = @"发送重启成功，请稍后查看设备状态";
            UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [vc addAction:cancel];
//            [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            [JPToast showText:x[@"message"]];
        }
    } error:^(NSError *error) {
        [self hideLoading];
        [JPToast showText:@"网络错误"];
    }];
}

- (void)requestForUpdate{
    [self showLoading:@""];
    NSString *url = [NSString stringWithFormat:@"%@%@/cmd", d_cmd, mDeviceItem.sn];
    NSDictionary *dic = @{@"cmd": @"rom_upgrade", @"content": @"1"};
    [[[HttpRequest shareInstance] signPost:url map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        if ([x[@"code"] intValue] == 200) {
            [JPToast showText:@"正在升级，请稍后查看"];
        } else {
            [JPToast showText:x[@"message"]];
        }
    } error:^(NSError *error) {
        [self hideLoading];
        [JPToast showText:@"网络错误"];
    }];
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
